#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h> 
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define CONNECT_TIMES 3

/* 联网 */
/* 
    @brief:      联网
    @argument1:  IP地址
    @argument2:  端口
    @return:     通信句柄
*/
int accessNetwork(const char * ip, int port)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("socket error");
        exit(-1);
    }
    //printf("sockfd is %d\n", sockfd);

    struct sockaddr_in localAddress;
    /* 所有的结构体定义都要清楚脏数据 */
    memset(&localAddress, 0, sizeof(localAddress));
    localAddress.sin_family = AF_INET;          // ipv4
    localAddress.sin_port = htons(port);

    // /* 将小端点分十进制的IP地址 转换为大端的网络字节序 */
    // const char * ip = "172.23.194.60";
    inet_pton(AF_INET, ip, &(localAddress.sin_addr.s_addr));


    socklen_t localAddressLength = sizeof(localAddress);


    int cnt = CONNECT_TIMES;
    while (cnt == -1)
    {
        int ret = connect(sockfd, (const struct sockaddr *)&localAddress, localAddressLength);
        if (ret == -1)
        {
            perror("connect error");
            sleep(1);
        }
        else
        {
            /* 程序执行到这个地方，联网成功 */
            break;
        }
        

    }
    return sockfd;
}